from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import json
from urllib.parse import urlparse, parse_qs
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        # 添加 CORS 头
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, token')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        return super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

    # 配置远端 WMS 服务
    REMOTE_BASE = 'http://172.24.2222.10/wms-web/invweb/eoOrderInterfaceController'
    REMOTE_RECEIVE = 'http://172.24.2222.10/wms-web/inbweb/inboundRcvController/receidBySnCode.shtml'
    REMOTE_KEY = '223679F'

    # 拣货相关API配置
    REMOTE_PICK_BASE = 'http://172.24.2222.10/wms-web/rfweb/screenSoController'

    def _proxy_get(self, remote_url: str):
        try:
            req = Request(remote_url, headers={'Content-Type': 'application/json'})
            with urlopen(req, timeout=15) as res:
                data = res.read()
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                self.wfile.write(data)
        except HTTPError as e:
            self.send_response(e.code)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(json.dumps({'code': e.code, 'msg': str(e)}).encode('utf-8'))
        except URLError as e:
            self.send_response(502)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(json.dumps({'code': 502, 'msg': f'Bad Gateway: {e}'}).encode('utf-8'))

    def _proxy_post(self, remote_url: str, body_bytes: bytes):
        try:
            req = Request(remote_url, data=body_bytes, headers={'Content-Type': 'application/json'}, method='POST')
            with urlopen(req, timeout=15) as res:
                data = res.read()
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                self.wfile.write(data)
        except HTTPError as e:
            self.send_response(e.code)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(json.dumps({'code': e.code, 'msg': str(e)}).encode('utf-8'))
        except URLError as e:
            self.send_response(502)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(json.dumps({'code': 502, 'msg': f'Bad Gateway: {e}'}).encode('utf-8'))

    def do_GET(self):
        parsed = urlparse(self.path)
        if parsed.path.startswith('/api/'):  # 反向代理入口
            qs = parse_qs(parsed.query)
            if parsed.path == '/api/orders':
                project_id = qs.get('projectId', [''])[0]
                whCode = qs.get('whCode', ['ZB001'])[0]  # 默认值
                userCode = qs.get('userCode', ['Test'])[0]  # 默认值
                # 构建URL，确保参数正确传递
                url = f"{self.REMOTE_BASE}/findScreenOrderByWhcode.shtml?whCode={whCode}&userCode={userCode}&key={self.REMOTE_KEY}"
                print(f"API请求: whCode={whCode}, userCode={userCode}")
                print(f"请求URL: {url}")
                return self._proxy_get(url)
            if parsed.path == '/api/items':
                project_id = qs.get('projectId', [''])[0]
                asn_no = qs.get('asnNo', [''])[0]
                url = f"{self.REMOTE_BASE}/findScreenSkyByOrder.shtml?projectId={project_id}&asnNo={asn_no}&key={self.REMOTE_KEY}"
                return self._proxy_get(url)
            if parsed.path == '/api/pendingSNs':
                project_id = qs.get('projectId', [''])[0]
                asn_no = qs.get('asnNo', [''])[0]
                sku_code = qs.get('skuCode', [''])[0]
                url = f"{self.REMOTE_BASE}/findScreenSnBySku.shtml?projectId={project_id}&asnNo={asn_no}&skuCode={sku_code}&key={self.REMOTE_KEY}"
                return self._proxy_get(url)
            # 拣货相关API
            if parsed.path == '/api/pickOrders':
                wh_code = qs.get('whCode', [''])[0]
                user_code = qs.get('userCode', [''])[0]
                url = f"{self.REMOTE_PICK_BASE}/pickScreenListByWhcode.shtml?whCode={wh_code}&userCode={user_code}"
                return self._proxy_get(url)
            if parsed.path == '/api/pickItems':
                project_id = qs.get('projectId', [''])[0]
                so_no = qs.get('soNo', [''])[0]
                user_code = qs.get('userCode', [''])[0]
                url = f"{self.REMOTE_PICK_BASE}/pickSkuListByOrder.shtml?projectId={project_id}&soNo={so_no}&userCode={user_code}"
                return self._proxy_get(url)
            # 未匹配的 api 路径
            self.send_response(404)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            self.wfile.write(json.dumps({'code': 404, 'msg': 'Unknown API'}).encode('utf-8'))
            return
        # 静态文件
        return super().do_GET()

    def do_POST(self):
        parsed = urlparse(self.path)
        if parsed.path == '/api/receive':
            length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(length) if length > 0 else b'{}'
            print(f"收到收货请求: {body.decode('utf-8')}")
            url = self.REMOTE_RECEIVE
            return self._proxy_post(url, body)
        if parsed.path == '/api/pickBySn':
            length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(length) if length > 0 else b'{}'
            url = f"{self.REMOTE_PICK_BASE}/pkBySnCode"
            return self._proxy_post(url, body)
        return super().do_POST()

def run(server_class=HTTPServer, handler_class=CORSRequestHandler, port=9005):
    server_address = ('', port)

    httpd = server_class(server_address, handler_class)
    print(f"Starting server on port {port}...")
    print(f"Visit http://172.24.2222.10:{port}/receive_goods.html")
    print(f"Visit http://172.24.2222.10:{port}/pick_goods.html")
    httpd.serve_forever()

if __name__ == '__main__':
    # 确保在正确的目录下运行
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    run() 